<template>
  <el-cascader
    popper-class="cascader-hide-radio-new"
    ref="areaRef"
    v-model="area"
    :props="treeProps"
    placeholder="请选择"
    :disabled="disabled"
    :style="{ width: width }"
    :clearable="props.clearable"
    @change="changeSelect"
  />
</template>

<script setup>
import { get_area_list, get_org_list } from '@/api/system'
// 全部区划
const emit = defineEmits([
  'update:areaCode',
  'update:orgCode'
])
const props = defineProps({
  areaCode: {
    type: [String, Number],
    default: ''
  },
  orgCode: {
    type: [String, Number],
    default: ''
  },
  clearable: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  width: {
    type: String,
    default: '210px'
  },
  // 父子强制关联 true:可选任意一级  false:只能选中最后一级
  strictly: {
    type: Boolean,
    default: true
  }
})
const areaRef = ref(null)
const area = computed({
  get() {
    return `${props.areaCode}`
  },
  set() {}
})
const calLeaf = (item, level) => {
  return !item.hasChildren
}
const treeProps = computed(() => {
  if (areaRef.value) {
    return {
      lazy: true,
      label: 'name',
      checkStrictly: true,
      lazyLoad: async (node, resolve) => {
        const { data, level } = node
        if (level === 0) {
          const r = await getArea()
          const targetData = []
          for (const item of r.data) {
            const temp = {
              id: item.id,
              name: item.name,
              value: item.id,
              leaf: false
            }
            targetData.push(temp)
          }
          resolve(targetData)
        } else {
          console.log('data', data)
          const r = await getOrg({
            orgType: 1,
            areaCode: data.id
          })
          const targetData = []
          for (const item of r.data) {
            const temp = {
              id: item.id,
              name: item.orgName,
              value: item.orgCode,
              leaf: true
            }
            targetData.push(temp)
          }
          const pathLabels = areaRef.value.getCheckedNodes()[0]
          resolve(targetData)
        }
      }
    }
  } else {
    return {}
  }
})


onMounted(() => {})
const changeSelect = val => {
  emit('update:areaCode', val[0] ? val[0] : '')
  emit('update:orgCode', val[1] ? val[1] : '')
  areaRef.value.getCheckedNodes()[0].isLeaf &&
    areaRef.value.togglePopperVisible(false)
}

const getArea = () => {
  return get_area_list()
}
const getOrg = code => {
  return get_org_list(code)
}
</script>

<style lang="scss" scoped></style>
